import SchemaFormModal, { SchemaFormModalRef } from '@/components/Element/SchemaFormModal';
import service from '@/services';
import useMessage from 'antd/es/message/useMessage';
import React, { useImperativeHandle, useRef } from 'react';
import { getTableFieldsList } from '../config/edit';
import EditFormConfig from '../json/edit.json';

interface EditModalProps {
  onCancel?: () => void;
  onSubmit?: (formData: any) => void;
  title?: any;
}

const UpdateModal = React.forwardRef<any, EditModalProps>((props, ref) => {
  const { onCancel, onSubmit } = props || {};
  const formRef = useRef<SchemaFormModalRef>(null);
  const [messageApi, messageContextHolder] = useMessage();

  const handleOpen = (values: any) => {
    console.log('UpdateModal handleOpen called with:', values);
    try {
      formRef.current?.show(values);
    } catch (error) {
      console.error('UpdateModal show error:', error);
    }
  };

  useImperativeHandle(ref, () => ({
    handleOpen,
  }));

  const handleFinish = async (values: any) => {
    console.log('UpdateModal handleFinish called with:', values);
    const res = await service.code.edit(values.id, values);
    if (res.code === 200) {
      messageApi.success('操作成功');
      if (onSubmit) {
        try {
          onSubmit(values);
        } catch (error) {
          console.error('EditModal onSubmit error:', error);
        }
      }
      return true;
    } else {
      messageApi.error(res.msg);
      return false;
    }
  };

  const handleCancel = () => {
    console.log('UpdateModal handleCancel called');
    try {
      formRef.current?.dismiss();
    } catch (error) {
      console.error('UpdateModal dismiss error:', error);
    }
    if (onCancel) {
      try {
        onCancel();
      } catch (error) {
        console.error('UpdateModal onCancel error:', error);
      }
    }
  };

  return (
    <>
      <SchemaFormModal
        modalProps={{
          title: props.title,
          width: '60vw',
          onOpenChange: (open: boolean) => {
            if (!open) handleCancel();
          },
        }}
        fields={getTableFieldsList(EditFormConfig, 'edit')}
        ref={formRef}
        onFinish={handleFinish}
      />
      {messageContextHolder}
    </>
  );
});

export default UpdateModal;
